package com.bosssoft.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.bosssoft.oss.dao.FileDao;
import com.bosssoft.oss.utils.OssServer;
import com.bosssoft.oss.pojo.FileUpAndDown;
import com.bosssoft.oss.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OssServer ossServer;
    @Autowired
    private OSSClient ossClient;
    @Autowired
    private FileDao fileDao;

    /**
     * 文件的上传
     * @param multipartFile
     * @return
     */
    @Override
    public FileUpAndDown upload(MultipartFile multipartFile) {

        FileUpAndDown fileUpAndDown = new FileUpAndDown();
        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        File file = fileDao.getFile(filePath);
        //上传至阿里云仓库
        try {
            ossClient.putObject(ossServer.getBucketName(), fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
            fileUpAndDown.setStatus("failed");
            return fileUpAndDown;
        }
        fileUpAndDown.setStatus("over");
        fileUpAndDown.setResult("success");
        fileUpAndDown.setFname(ossServer.getUrlPrefix() + filePath);
        fileUpAndDown.setFid(String.valueOf(System.currentTimeMillis()));
        return fileUpAndDown;

    }

    /**
     * @param ossClient
     * @param objectName
     * @throws IOException
     */
    @Override
    public void download (OSSClient ossClient, String objectName,String path) throws IOException {
        fileDao.saveFile(ossServer.OSSClient(),ossServer.getBucketName(),path,objectName);

    }

    /**
     * 生成路径以及文件名
     * @param fileName 文件名
     * @return
     */
    @Override
    public String getFilePath(String fileName) {

        //获取文件后缀名
        String ext=fileName.substring(fileName.lastIndexOf("."));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        String date = sdf.format(new Date());

        String uuid = UUID.randomUUID().toString().replace("-", "");

        return "document/"+date+"/"+uuid+ext;
    }
}
